;;somewhat done, not quite
%include "asm_io.inc"

%define x			qword [ebp+8]
%define root		qword [ebp+16]
%define negative	dword [ebp - 4]
%define temp		qword [ebp - 12]
segment .data
;
;initialized data is put in the data segment here
;

segment .bss
;
;uninitialized data is put in the bss segment
;

segment .text
;
;code here
;
	global croot

croot:
	enter 12,0				;setup
	pushad
	
	mov dword negative, 0	;assume we are not negative
	
	fldz					;ST0 = 0
	fcom x					;x > 0 ?
	fstsw ax				;store result ax
	sahf					;update flags
	
	fadd x					;ST0 = 0 + x
	
	jna not_negative		;if 0<x, dont do anything
	
		mov dword negative, 1	;if 0>x, remember for later
		fabs					;x = |x|
not_negative:	
	
	fsqrt					;ST0 = root(ST0)
	fst temp				;temp = ST0
	
	mov ebx,2				;start with 2 
	mov edx, 1
	mov eax, -1
	call print_int
outer_loop:
		mov ecx, ebx		;reset our loop counter
		inner_loop:
			fsqrt			;ST0 = root(ST0)
			loop inner_loop
		
		cmp edx, 30			;check if we are close enough
		je end_outer_loop	;do the jump
		
		add edx,1
		fmul temp			;ST0 *= temp
		fst temp			;temp = ST0
		shl ebx, 1			;#loops = #loops * 2
		mov edx, eax
		call print_int
		jmp outer_loop
end_outer_loop:		
		fmul temp			;ST0 *= temp
		fsqrt				;ST0 = root(ST0)
		
		cmp negative, 1		;checks if we had a negative
		jne report			;if we didn't, we go to return
		
		fchs				;flips the sign of our result
report:
		fst root			;returns result
		
	;do not remove code af ter this
	popad
	mov eax,0	;return back to C
	leave
	ret
	